<script setup lang="ts">
import {computed, reactive, ref} from "vue";
import {type ComponentSize, ElMessage, type FormInstance, type FormRules} from "element-plus";
import {Lock} from "@element-plus/icons-vue";
import {sendCodeToUpdatePasswordApi, updatePasswordApi} from "@/api/client/user.ts";

interface ChangeForm {
  phone: string
  code: string
  password: string
  passwordRepeat: string
}

const formSize = ref<ComponentSize>('large')
const changeRef = ref<FormInstance>()
const changeForm = reactive<ChangeForm>({
  phone: '',
  code: '',
  password: '',
  passwordRepeat: ''
})

const rules = reactive<FormRules<ChangeForm>>({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {
      min: 6,
      max: 20,
      message: '密码长度必须在6到20位之间',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: '密码只能包含数字、大小写字母',
      trigger: 'blur'
    }
  ],
  passwordRepeat: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {
      min: 6,
      max: 20,
      message: '密码长度必须在6到20位之间',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: '密码只能包含数字、大小写字母',
      trigger: 'blur'
    },
  ]
})

const emit = defineEmits(['closeUpdatePasswordDialog'])

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (changeForm.password !== changeForm.passwordRepeat) {
          ElMessage.warning('两次输入的密码不一致')
          return
        }
        await updatePasswordApi(changeForm.phone, changeForm.code, changeForm.password, changeForm.passwordRepeat)
        emit('closeUpdatePasswordDialog')
      } catch (e: any) {
        ElMessage.error(e)
      }
    } else {
      ElMessage.warning('请输入合法的手机号或验证码')
    }
  })
}

const phoneRegion = ref('+86')

const isCounting = ref(false); // 是否正在倒计时
const countdown = ref(60); // 倒计时时间
const buttonText = computed(() => (isCounting.value ? `${countdown.value}秒后重试` : '获取验证码'));

// 校验手机号是否有效
const isPhoneValid = computed(() => /^1[3-9]\d{9}$/.test(changeForm.phone));

// 处理获取验证码逻辑
const handleGetCode = async () => {
  if (!isPhoneValid.value) {
    return;
  }
  // 发送验证码请求
  try {
    await sendCodeToUpdatePasswordApi(changeForm.phone)
    ElMessage.success('验证码发送成功')
    // 禁用按钮并开始倒计时
    isCounting.value = true;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value === 0) {
        clearInterval(timer);
        isCounting.value = false;
        countdown.value = 60; // 重置倒计时
      }
    }, 1000);
  } catch (e:any) {
    ElMessage.error(e)
  }
};
</script>

<template>
  <el-form
      ref="changeRef"
      style="max-width: 600px"
      :model="changeForm"
      :rules="rules"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
  >
    <div class="phone">
      <el-select v-model="phoneRegion" placeholder="+86" style="width: 80px">
        <el-option label="+86" value="+86"/>
      </el-select>
      <el-form-item prop="phone">
        <el-input
            v-model="changeForm.phone"
            style="width: 220px"
            placeholder="输入手机号"
        >
        </el-input>
      </el-form-item>
    </div>
    <el-form-item prop="smsCode">
      <el-input
          v-model="changeForm.code"
          style="width: 300px;"
          placeholder="验证码"
      >
        <template #append>
          <el-button
              :disabled="!isPhoneValid || isCounting"
              :style="{
                    color: isPhoneValid && !isCounting
                        ? '#007AFF'
                        : '#C0C4CC',
                  }"
              @click="handleGetCode"
          >
            {{ buttonText }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="password">
      <el-input
          v-model="changeForm.password"
          style="width: 300px"
          placeholder="请输入密码"
          type="password"
          show-password
          :prefix-icon="Lock"
      >
      </el-input>
    </el-form-item>

    <el-form-item prop="password">
      <el-input
          v-model="changeForm.passwordRepeat"
          style="width: 300px"
          placeholder="请再次输入密码"
          type="password"
          show-password
          :prefix-icon="Lock"
      >
      </el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(changeRef)">
        确认
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.el-form {
  .phone {
    width: 300px;
    display: flex;
  }

  .el-form-item:last-child {
    .el-button {
      width: 300px;
      background-color: #242528;
    }
  }
}
</style>